package com.sgcc.epri.dcloud.service.impl;

import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sgcc.epri.dcloud.mapper.dm.ManagementUnitMapper;
import com.sgcc.epri.dcloud.pojo.ManagementUnit;
import com.sgcc.epri.dcloud.pojo.Result;
import com.sgcc.epri.dcloud.service.ManagementUnitService;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.CompletableFuture;

@Service
public class ManagementUnitServiceImpl implements ManagementUnitService {

    private final Logger log =  LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ManagementUnitMapper managementUnitMapper;

    @Override
    public Result select(String treeId) {
        try{
            QueryWrapper<ManagementUnit> muqw = new QueryWrapper<>();
            muqw.eq("parent_id", treeId);
            muqw.orderByAsc("sort");
            return Result.success(managementUnitMapper.selectList(muqw));
        }catch (Exception e){
            e.printStackTrace();
            log.error("查询失败！");
            return Result.error("查询失败！");
        }
    }

    @Override
    public Result update(ManagementUnit managementUnit) {
        try {
            return Result.success(managementUnitMapper.updateById(managementUnit));
        }catch (Exception e){
            e.printStackTrace();
            log.error("修改失败！");
            return Result.error("修改失败！");
        }
    }

    @Override
    public Result insert(ManagementUnit managementUnit) {
        try{
            if(managementUnit.getDatasource() == null || managementUnit.getName() == null)return Result.success("名称或数据源id不得为空");
            QueryWrapper<ManagementUnit> muqw = new QueryWrapper<>();
            muqw.eq("parent_id", managementUnit.getParentId());
            muqw.eq("datasource", managementUnit.getDatasource());
            Integer integer = managementUnitMapper.selectCount(muqw);
            if (integer != 0 && managementUnit.getHiddenFlag() == null) {
                return Result.success("不允许录入重复的数据源");
            }else {
                if (managementUnit.getHiddenFlag() == null || managementUnit.getHiddenFlag().equals("")) {
                    managementUnit.setHiddenFlag("1");
                }
            }
            return Result.success(managementUnitMapper.insert(managementUnit));
        }catch (Exception e){
            e.printStackTrace();
            log.error("插入失败！");
            return Result.error("插入失败！");
        }
    }

    @Override
    public Result delete(String id) {
        try{
            return Result.success(managementUnitMapper.deleteById(id));
        }catch (Exception e){
            e.printStackTrace();
            log.error("删除失败！");
            return Result.error("删除失败！");
        }
    }

    @Transactional
    @Override
    public Result upOrDown(String hostId, String rmId) {
        try{

            CompletableFuture<ManagementUnit> hostFuture = querySortById(hostId);
            CompletableFuture<ManagementUnit> rmFuture = querySortById(rmId);

            // 等待sql执行
            CompletableFuture.allOf(hostFuture, rmFuture).join();

            if(hostFuture.get() == null || rmFuture.get() == null) return Result.error("参数有误");

            QueryWrapper<ManagementUnit> muqwHost = new QueryWrapper<>();
            muqwHost.eq("id", hostId);
            ManagementUnit hostTableHead = new ManagementUnit();
            hostTableHead.setSort(rmFuture.get().getSort());
            managementUnitMapper.update(hostTableHead, muqwHost);

            QueryWrapper<ManagementUnit> muqwRm = new QueryWrapper<>();
            muqwRm.eq("id", rmId);
            ManagementUnit rmTableHead = new ManagementUnit();
            rmTableHead.setSort(hostFuture.get().getSort());
            managementUnitMapper.update(rmTableHead, muqwRm);

            return Result.success("修改成功");
        }catch (Exception e){
            e.printStackTrace();
            log.error("修改失败"+e);
            return Result.error("修改失败");
        }
    }

    @Autowired
    @Qualifier("dmSqlSessionFactory")
    private SqlSessionFactory sqlSessionFactory;

    @Transactional
    @Override
    public Result oneClickImport(String treeId, String type, String referToTreeId) {
        // 关闭session的自动提交
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
        try{
            ManagementUnitMapper managementUnitMapper = sqlSession.getMapper(ManagementUnitMapper.class);

            // 删除原有数据
            QueryWrapper<ManagementUnit> muqw = new QueryWrapper<>();
            muqw.eq("parent_id",treeId);
            managementUnitMapper.delete(muqw);

            if (type.equals("101")) {
                ManagementUnit managementUnit = new ManagementUnit();
                managementUnit.setDatasource("0021990101_no");
                managementUnit.setName("华北（不含蒙西）");
                List<ManagementUnit> datasource = managementUnitMapper.queryDataSource();
                datasource.add(managementUnit);
                datasource.forEach(mu -> {mu.setParentId(treeId);mu.setSort(NumberUtil.generateRandomNumber(1, 99999, 1)[0]+"");mu.setHiddenFlag("1");});
                // 批量插入
                datasource.forEach(managementUnitMapper::insert);
            } else if (type.equals("102")){
                QueryWrapper<ManagementUnit> muqwCOPY = new QueryWrapper<>();
                muqwCOPY.eq("parent_id", referToTreeId);
                List<ManagementUnit> mmu = managementUnitMapper.selectList(muqwCOPY);
                mmu.forEach(mu -> {mu.setId(null);mu.setParentId(treeId);managementUnitMapper.insert(mu);mu.setHiddenFlag("1");});
            }

            // 提交数据
            sqlSession.commit();
            return Result.success("一键导入成功");
        }catch (Exception e){
            e.printStackTrace();
            log.error("一键导入失败"+e);
            return Result.error("一键导入失败");
        }finally {
            sqlSession.close();
        }
    }

    @Override
    public Result queryManagementUnit() {
        try{
            List<ManagementUnit> managementUnits = managementUnitMapper.queryManagementUnit();
            ManagementUnit managementUnit = new ManagementUnit();
            managementUnit.setDatasource("0021990101_no");
            managementUnit.setName("华北（不含蒙西）");
            managementUnits.add(managementUnit);
            return Result.success(managementUnits);
        }catch (Exception e){
            e.printStackTrace();
            log.error("查询治理单位失败");
        }
        return Result.error("查询治理单位失败!");
    }

    @Async("threadPoolTaskExecutor")
    public CompletableFuture<ManagementUnit> querySortById(String id){
        try{
            QueryWrapper<ManagementUnit> oqw = new QueryWrapper<>();
            oqw.eq("id",id);
            return CompletableFuture.completedFuture(managementUnitMapper.selectOne(oqw));
        }catch (Exception e){
            e.printStackTrace();
            log.error("Error executing SQL query: {}", e);
            return null;
        }
    }
}
